<template>
    <n-card :bordered="false" class="proCard">
        <BasicForm @register="register"  @submit="handleSubmit">
        <template #gameSelect="{ model, field }">
            <n-select v-model:value="model[field]" :options="gameOptions" clearable />
        </template>
        <template #customerSelect="{ model, field }" v-if="roleType === 'admin' || roleType === 'super' ">
            <n-select v-model:value="model[field]" :options="customerOptions" clearable />
        </template>
        </BasicForm>

        <BasicTable ref="actionRef" :columns="columns" :row-key="(row) => row.id" :request="loadDataTable" @update:checked-row-keys="onCheckedRow" :actionColumn="actionColumn" :scroll-x="2048">
            <template #toolbar>
                <n-button type="primary" @click="reloadTable">刷新数据</n-button>
            </template>
        </BasicTable>
    </n-card>
    
    <basicModal ref="modalRef" class="basicModal" style="width: 30%" @register="modalRegister" @on-ok="okModal">
        <template #default>
        <BasicForm class="basicForm" @register="editCustomer">
            <template #recordTypeMap="{ model, field }">
            <n-select v-model:value="model[field]" :options="recordTypeMap" clearable />
            </template>
        </BasicForm>
        </template>
    </basicModal>
</template>
  
<script lang="ts" setup>
import {ref,reactive,onMounted,unref ,h} from 'vue';
import { BasicTable,TableAction } from '@/components/Table';
import { columns,editCloumns,schemas } from './index';
import { CustomerRecordList,CustomerAccountList ,CustomerEdit} from '@/api/statistics/daily';
import { BasicForm, useForm } from '@/components/Form/index';
import { getGameAll } from '@/api/game/game';
import { useUserStore } from '@/store/modules/user';
import { useMessage } from 'naive-ui';
import { EditOutlined} from '@vicons/antd';
import {useModal} from "@/components/Modal";
import {FormSchema} from "@/components/Form";
const roleType = ref('')
const actionRef = ref()
const gameOptions = ref([])
const customerOptions = ref([])
const isEdit = ref(false)
const message = useMessage()
const updateValue = ref();
const formParams = reactive({
    roleId: '',
    userId: 0,
    gameName:'',
    customerId:'',
    loseStatus:'1',
    recordStatus:'1',
    pageSize:10,
    page:1,
});

const recordTypeMap = [
    {value:'BasicMaintenance',label:'基础维护'},
    {value:'UserSurvey',label:'用户问卷调查'},
    {value:'GameContentPush',label:'游戏内容推送'},
    {value:'GiftPackSending',label:'礼包发送'}
]

const [editCustomer, { submit: editSubmit, setFieldsValue: addSetFieldsValue }] = useForm({
    gridProps: { cols: 1 },
    collapsedRows: 3,
    labelWidth: 120,
    layout: 'horizontal',
    submitButtonText: '提交保存',
    showActionButtonGroup: false,
    schemas: editCloumns,
});


async function okModal() {
    let formValue;
    try {
      formValue = await editSubmit();
    } catch (e) {
      message.error('请填写完整信息');
    } finally {
      setSubLoading(false);
    }
    formValue.id = updateValue.value.id
    try {
        await CustomerEdit(formValue);
        closeModal();
    } finally {
      setSubLoading(false);
    }

    await reloadTable();
}

const [modalRegister, {openModal,closeModal, setSubLoading, setProps}] = useModal({
    title: '编辑',
});


onMounted(async () => {
    roleType.value = useUserStore().getRoleType
    if (roleType.value === 'admin' || roleType.value === 'super'){
        const hasCustomerIdColumn = schemas.some((column: FormSchema) => {
            return column.field === 'customerId';
        });
        if(!hasCustomerIdColumn){
          schemas.push({
            field: 'customerId',
            label: '客服编号:',
            slot: 'customerSelect',
          },)
        }

if (hasCustomerIdColumn) {
  // 存在客服编号字段
} else {
  // 不存在客服编号字段
}
    }
    let gameVal = await getGameAll();
    gameOptions.value = gameVal.map((value) => {
      return {
        label: value.gameName,
        value: value.gameId,
      };
    });
    let userVal = await CustomerAccountList();
    customerOptions.value = userVal.map((value) => {
      return {
        label: value.username,
        value: value.phone,
      };
    });
});


const [register, {}] = useForm({
    gridProps: {cols: 6},
    labelWidth: 80,
    schemas,
});

const loadDataTable = async (res) => {
    const param = { ...formParams, ...res };
    param.userId = param.userId === '' ? 0 :Number(param.userId);
    const data = await CustomerRecordList(param);
    console.log(data);
    return data
};

function reloadTable() {
    actionRef.value.reload();
}

function handleSubmit(values: Recordable) {
    let tempParams = unref(formParams);
    tempParams = Object.assign(tempParams, values);
    reloadTable();
}

const actionColumn = reactive({
    width: 120,
    title: '操作',
    key: 'action',
    fixed: 'right',
    render(record) {
      return h(TableAction as any, {
        style: 'button',
        actions: [
          {
            label: '编辑',
            onClick: handleEditBtnClick.bind(null, record),
            type: 'info',
            icon: EditOutlined,
            ifShow: () => {
              return true;
            },
          },
        ],
        select: (key) => {
          message.info(`您点击了，${key} 按钮`);
        },
      });
    },
});

//编辑按钮点击响应
async function handleEditBtnClick(record: Recordable) {
    isEdit.value = true;
    await openModal();
    setProps({ title: '编辑' });
    updateValue.value = record;
    addSetFieldsValue(updateValue.value);
  }

function onCheckedRow(rowKeys) {
    console.log(rowKeys)
    // recordReqList.value = rowKeys
}


</script>
  